package com.example.lib_mvp.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class CustomWaveformView extends View {

    private Paint paint;
    private List<Float> amplitudes;
    private int barWidth;
    private int spacing;
    private Random random;
    private byte[] amplitudesByte;

    public CustomWaveformView(Context context) {
        this(context, null);
    }

    public CustomWaveformView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomWaveformView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);
        amplitudes = new ArrayList<>();
        barWidth = 8; // 每个柱子的宽度
        spacing = 4;  // 柱子之间的间距
        random = new Random();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();

        float maxAmplitude = getMaxAmplitude(amplitudes);
        for (int i = 0; i < amplitudes.size(); i++) {
            float amplitude = amplitudes.get(i);
            float barHeight = (amplitude / maxAmplitude) * height;
            int x = i * (barWidth + spacing);
            // 添加随机波动
            float randomOffset = random.nextFloat() * 0.2f - 0.1f; // 随机波动范围 ±10%
            barHeight *= (1 + randomOffset);
            canvas.drawRect(x, height - barHeight, x + barWidth, height, paint);
        }
    }

    private float getMaxAmplitude(List<Float> amplitudes) {
        float max = 0;
        for (float amp : amplitudes) {
            if (amp > max) {
                max = amp;
            }
        }
        return max;
    }

    public void addAmplitude(float amplitude) {
        if (amplitudes.size() > 30) {
            amplitudes.set(random.nextInt(30), amplitude);
        } else {
            amplitudes.add(amplitude);
        }
        invalidate(); // 请求重新绘制
    }

    public void clearAmplitudes() {
        amplitudes.clear();
        invalidate(); // 请求重新绘制
    }
}
